package com.example.yiqinmanagersystem.controller.api;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.http.HttpResponse;
import com.example.yiqinmanagersystem.entity.User;
import com.example.yiqinmanagersystem.service.UserService;
import com.example.yiqinmanagersystem.vo.ResponseResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/*
 **@Author:youpeng
 **Created on 2022/9/14
 */
@RestController
@RequestMapping("/api")
public class LoginController {

    @Resource
    private UserService userService;

    /*
    * 用户登录逻辑
    * */
    @PostMapping("/login/login")
    public ResponseResult login(String username,String password,String code,HttpSession session){
        //1.验证验证码是否正确
        String sessionCode = (String) session.getAttribute("code");
        if(sessionCode!=null && sessionCode.equals(code)){
            //2.登录逻辑
            //2.1普通登录
//            User user = userService.login(username,password);
            //2.2shrio登录
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, DigestUtils.md5DigestAsHex(password.getBytes()));
            subject.login(token);
            User user = (User) subject.getPrincipal();
            //3.判断登录
            if(user!=null){
                session.setAttribute("user",user);
                return new ResponseResult("200","登录成功",user);
            }else {
                return new ResponseResult("500","用户名或密码不正确，登录失败",null);
            }
        }
        return new ResponseResult("500","验证码不正确，登录失败",null);
    }

    /*
    * 获取图片验证码
    * */
    @GetMapping("/login/getCode")
    public ResponseResult getCode(HttpServletResponse response , HttpSession session){
        //1.验证码对象
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(116, 36, 4, 10);
        //2.放入session
        session.setAttribute("code",captcha.getCode());
        //3.输出
        try(ServletOutputStream outputStream = response.getOutputStream();) {
            captcha.write(outputStream);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ResponseResult("200","获取验证码成功",null);
    }

}
